package com.venus.config.shiro;

import com.venus.common.Commons;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 设置拦截器，未登录请求统一跳转到登录页面
 */
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {

	@Override
	public void addInterceptors(final InterceptorRegistry registry) {
		registry.addInterceptor(new SecurityInterceptor())
				.addPathPatterns("/**")
				.excludePathPatterns("/base/**", "/rest/**", "/logout/**", "/error/**","/swagger*/**","/webjars/**","/v2*/**");
		super.addInterceptors(registry);
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("swagger-ui.html")
				.addResourceLocations("classpath:/META-INF/resources/");

		registry.addResourceHandler("/webjars/**")
				.addResourceLocations("classpath:/META-INF/resources/webjars/");
	}

	/**
	 * 内部拦截器类
	 */
	private class SecurityInterceptor implements HandlerInterceptor {

		@Override
		public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
			Object sessionObj = httpServletRequest.getSession().getAttribute(Commons.SESSION_USER_KEY);
			if(null != sessionObj) {
				return true;
			}
			httpServletResponse.sendRedirect(Commons.LOGIN_URL);
			return false;
		}

		@Override
		public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

		}

		@Override
		public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

		}
	}
}